import { RouteRecordRaw, createWebHashHistory, createRouter } from "vue-router";
import { useStore } from "../store";
import { GetDynamicRoutes } from "../apis";

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        redirect: '/Home'
    },
    {
        path: '/Home',
        component: () => import('../views/home.vue')
    },
    {
        path: '/:catchAll(.*)',
        component: ()=> import('../views/Error/404.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    if(to.path !== '/Home' && to.path !== '/') {
        const store = useStore();
        if(store.routes.length < 1) {
            GetDynamicRoutes().then(res=> {
                store.addRoutes(res.data.data, router)
                next({ path: to.path, replace: true })
            }).catch(_ => {
                next()
            })
        } else {
            next()
        }
    } else {
        next()
    }
})

export default router